package com.docmgmt.mvp.controller;

import com.docmgmt.mvp.dto.Result;
import com.docmgmt.mvp.ragflow.RAGFlowClient;
import com.docmgmt.mvp.ragflow.dto.ChunkDetailVO;
import com.docmgmt.mvp.ragflow.dto.ChunkRetrievalRequest;
import com.docmgmt.mvp.ragflow.dto.ChunkRetrievalResultVO;
import com.docmgmt.mvp.ragflow.dto.UpdateChunkRequest;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * RAGFlow Chunk 管理 Controller
 * 
 * 提供 Chunk 的列表、删除、更新、检索接口
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/ragflow")
@RequiredArgsConstructor
@Tag(name = "RAGFlow Chunk 管理", description = "RAGFlow Chunk 列表、删除、更新、检索接口")
public class RAGFlowChunkController {

    private final RAGFlowClient ragFlowClient;

    /**
     * 列出指定文档的所有 Chunk
     *
     * GET /api/v1/ragflow/datasets/{datasetId}/documents/{documentId}/chunks
     *
     * @param datasetId  知识库ID
     * @param documentId 文档ID
     * @param keywords   关键词过滤（可选）
     * @param page       页码（从1开始）
     * @param pageSize   每页大小
     * @return Chunk列表
     */
    @GetMapping("/datasets/{datasetId}/documents/{documentId}/chunks")
    @PreAuthorize("hasAuthority('ragflow:chunk:read')")
    @Operation(summary = "列出文档的所有Chunk", description = "获取指定文档的所有Chunk，支持关键词过滤和分页")
    public Result<List<ChunkDetailVO>> listChunks(
            @PathVariable String datasetId,
            @PathVariable String documentId,
            @RequestParam(required = false) String keywords,
            @RequestParam(required = false) Integer page,
            @RequestParam(name = "page_size", required = false) Integer pageSize) {
        try {
            log.info("收到列出 Chunk 请求: dataset_id={}, document_id={}, keywords={}, page={}, pageSize={}", 
                    datasetId, documentId, keywords, page, pageSize);
            List<ChunkDetailVO> chunks = ragFlowClient.listChunks(datasetId, documentId, keywords, page, pageSize);
            log.info("列出 Chunk 成功: count={}", chunks.size());
            return Result.success(chunks);
        } catch (Exception e) {
            log.error("列出 Chunk 失败: dataset_id={}, document_id={}", datasetId, documentId, e);
            return Result.error("列出 Chunk 失败: " + e.getMessage());
        }
    }

    /**
     * 删除 Chunk
     *
     * DELETE /api/v1/ragflow/datasets/{datasetId}/documents/{documentId}/chunks
     *
     * @param datasetId   知识库ID
     * @param documentId  文档ID
     * @param requestBody 请求体，包含chunk_ids数组
     * @return 删除结果
     */
    @DeleteMapping("/datasets/{datasetId}/documents/{documentId}/chunks")
    @PreAuthorize("hasAuthority('ragflow:chunk:update')")
    @Operation(summary = "删除Chunk", description = "批量删除指定文档的Chunk")
    public Result<Void> deleteChunks(
            @PathVariable String datasetId,
            @PathVariable String documentId,
            @Valid @RequestBody Map<String, List<String>> requestBody) {
        try {
            List<String> chunkIds = requestBody.get("chunk_ids");
            
            if (chunkIds == null || chunkIds.isEmpty()) {
                return Result.error("Chunk ID列表不能为空");
            }

            log.info("收到删除 Chunk 请求: dataset_id={}, document_id={}, chunk_ids={}", 
                    datasetId, documentId, chunkIds);
            ragFlowClient.deleteChunks(datasetId, documentId, chunkIds);
            log.info("Chunk 删除成功: count={}", chunkIds.size());
            return Result.success("Chunk 删除成功");
        } catch (Exception e) {
            log.error("删除 Chunk 失败: dataset_id={}, document_id={}", datasetId, documentId, e);
            return Result.error("删除 Chunk 失败: " + e.getMessage());
        }
    }

    /**
     * 更新 Chunk 内容
     *
     * PUT /api/v1/ragflow/datasets/{datasetId}/documents/{documentId}/chunks/{chunkId}
     *
     * @param datasetId  知识库ID
     * @param documentId 文档ID
     * @param chunkId    Chunk ID
     * @param request    更新请求
     * @return 更新后的 Chunk 详情
     */
    @PutMapping("/datasets/{datasetId}/documents/{documentId}/chunks/{chunkId}")
    @PreAuthorize("hasAuthority('ragflow:chunk:update')")
    @Operation(summary = "更新Chunk内容", description = "更新指定Chunk的内容、关键词、可用状态")
    public Result<ChunkDetailVO> updateChunk(
            @PathVariable String datasetId,
            @PathVariable String documentId,
            @PathVariable String chunkId,
            @Valid @RequestBody UpdateChunkRequest request) {
        try {
            log.info("收到更新 Chunk 内容请求: dataset_id={}, document_id={}, chunk_id={}", 
                    datasetId, documentId, chunkId);
            ChunkDetailVO chunk = ragFlowClient.updateChunk(datasetId, documentId, chunkId, request);
            log.info("Chunk 内容更新成功: chunk_id={}", chunkId);
            return Result.success(chunk);
        } catch (Exception e) {
            log.error("更新 Chunk 内容失败: dataset_id={}, document_id={}, chunk_id={}", 
                    datasetId, documentId, chunkId, e);
            return Result.error("更新 Chunk 内容失败: " + e.getMessage());
        }
    }

    /**
     * 检索 Chunk（测试向量检索效果）
     *
     * POST /api/v1/ragflow/retrieval
     *
     * @param request 检索请求
     * @return 检索结果列表
     */
    @PostMapping("/retrieval")
    @PreAuthorize("hasAuthority('ragflow:chunk:read')")
    @Operation(summary = "检索Chunk", description = "根据查询文本检索相关Chunk，用于测试向量检索效果")
    public Result<List<ChunkRetrievalResultVO>> retrieveChunks(
            @Valid @RequestBody ChunkRetrievalRequest request) {
        try {
            log.info("收到检索 Chunk 请求: question={}, dataset_ids={}", 
                    request.getQuestion(), request.getDatasetIds());
            List<ChunkRetrievalResultVO> results = ragFlowClient.retrieveChunks(request);
            log.info("检索 Chunk 成功: count={}", results.size());
            return Result.success(results);
        } catch (Exception e) {
            log.error("检索 Chunk 失败: question={}", request.getQuestion(), e);
            return Result.error("检索 Chunk 失败: " + e.getMessage());
        }
    }
}

